import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {FormControl, FormGroup} from "@angular/forms";
import {RoleInfoService} from "../service/role-info.service";
import {RoleUser} from "../entity/role-user";
import {UserRoleService} from "../../services/user-role.service";
import {NzMessageService} from "ng-zorro-antd/message";

@Component({
  selector: 'app-role-users',
  templateUrl: './role-users.component.html',
  styleUrls: ['./role-users.component.less']
})
export class RoleUsersComponent implements OnInit {

  roleId: string
  roleName: string


  searchForm = new FormGroup({
    'userAccount': new FormControl(),
    'userName': new FormControl(),
    'enable': new FormControl(''),
    'isInclude': new FormControl('1')
  })


  users: RoleUser[]
  current = 1;
  pageSize = 20;
  count = 1000;
  pageSizes = [this.pageSize, 50, 100]
  loading = false


  constructor(private route: ActivatedRoute, private roleService: RoleInfoService, private roleUserService: UserRoleService, private msg: NzMessageService) {
  }

  ngOnInit(): void {

    this.roleId = this.route.snapshot.queryParams['pid']
    this.roleName = this.route.snapshot.queryParams['roleName']
    this.search()
  }


  search() {
    const param = this.searchForm.getRawValue()
    param.roleId = this.roleId
    this.loading = true
    this.roleService.getUsers(param, this.current, this.pageSize).subscribe(
      value => {
        this.users = value.data
        this.count = value.count || 1
        this.current = value.current || 1
        this.loading = false
      }, () => this.loading = false
    )

  }

  add(userId: string) {

    this.loading = true
    this.roleUserService.addRoleIds(userId, [this.roleId])
      .subscribe(value => {
        this.msg.success("添加成功");
        this.loading = false
        this.search()
      }, () => this.loading = false)
  }

  delete(userId: string) {
    this.loading = true
    this.roleUserService.delete(this.roleId, userId)
      .subscribe(value => {
        this.msg.success("删除成功");
        this.loading = false
        this.search()
      }, () => this.loading = false)
  }
}
